//
//  YCoAuthViewController.swift
//  swift微博
//
//  Created by 姚伟聪 on 15/12/16.
//  Copyright © 2015年 姚伟聪. All rights reserved.
//

import UIKit
import SVProgressHUD


class YCoAuthViewController: UIViewController,UIWebViewDelegate{

    //在这个方法里面这样直接赋值，系统会自动帮我们创建约束
    override func loadView() {
        view = webView
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let netWorkTool = YCNetWorkTool.shardNetWorkTool
        
        let url = netWorkTool.backAuthorizeURL()
        
        let request = NSURLRequest(URL: url)
        
        webView.loadRequest(request)
        webView.delegate = self
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "填充", style: UIBarButtonItemStyle.Plain, target: self, action: "stuffClick")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "cancelClick")
        
        
    }
    
    //MARK: - webView的代理方法
    func webViewDidStartLoad(webView: UIWebView) {
        
        SVProgressHUD.showWithStatus("正在加载", maskType: SVProgressHUDMaskType.Gradient)
    }
    func webViewDidFinishLoad(webView: UIWebView) {
        
        SVProgressHUD.dismiss()
        
    }
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        //URL转String
        let urlStr = request.URL!.absoluteString
       
        
        //判断前面是否包含uri，是就直接返回
        if !urlStr.hasPrefix(YCNetWorkTool.shardNetWorkTool.redirect_uri) {
        
//        print("这不是授权\(urlStr.hasPrefix(YCNetWorkTool.shardNetWorkTool.redirect_uri))")
            
            return true
        }
        
        //来到这里就说明是回调，所以要取code后面的值
        
        if let qurry = request.URL?.query {
        
           
            
            let NSQurry = qurry as NSString
            
            //判断qurry中前面是不是code = 
            let codeStr = "code="
            
            if qurry.hasPrefix(codeStr) {
                
                //从code=后面开始截取
                let code = NSQurry.substringFromIndex(codeStr.characters.count)
            
                //到这里就说明登录成功了
               ( UIApplication.sharedApplication().delegate as! AppDelegate).switchRootViewController(false)
                
                print("登录成功")
                loadAccessToken(code)
            }
            else{
                close()
            }
            
            
        
        }
        
        print("这是授权")
        
        return true
        
        
    }
    
    //MARK: - 发送Code码，取得Token的数据
    private func loadAccessToken(code: String) {
    
        YCNetWorkTool.shardNetWorkTool.loadAccessToken(code) { (result, error) -> Void in
            //这里就把result的数据传出去
            
            if let dict = result {
                //加载的是授权的信息
                let userAccount = YCUserAccount(dict: dict)
                userAccount.saveUserAccount()

           
            }
            
            
           
            
            
        
            
        }
        
    }
    
    func close(){
        SVProgressHUD.showErrorWithStatus("取消授权")
        dismissViewControllerAnimated(true, completion: nil)
    
    }
    
    
    //MARK: - 按钮点击
    func stuffClick(){
        // 创建js代码
        let js = "document.getElementById('userId').value='13726203163'; document.getElementById('passwd').value='159753';"
        
        // 让webView来执行js代码
        webView.stringByEvaluatingJavaScriptFromString(js)
        
    }
    
    func cancelClick(){
        
        dismissViewControllerAnimated(true, completion: nil)
        
    }
    
    
    //MARK: - 懒加载
    
    private lazy var webView: UIWebView = UIWebView()

}
